<?php

/**
 * 读取网易歌单数据
 * author:lovefc
 */
 
function setHead()
{
    return  array(
        'Referer'         => 'https://music.163.com/',
        'Cookie'          => 'appver=1.5.9; os=osx; __remember_me=true; osver=%E7%89%88%E6%9C%AC%2010.13.5%EF%BC%88%E7%89%88%E5%8F%B7%2017F77%EF%BC%89;',
        'User-Agent'      => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko)',
        'X-Real-IP'       => long2ip(mt_rand(1884815360, 1884890111)),
        'Accept'          => '*/*',
        'Accept-Language' => 'zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4',
        'Connection'      => 'keep-alive',
        'Content-Type'    => 'application/x-www-form-urlencoded',
    );
}

function neteaseHttp($url, $data = false)
{
    $SSL      = substr($url, 0, 8) == "https://" ? true : false; //判断是不是https链接
    $refer    = "http://music.163.com/";
    $head_arr = setHead();
    $header = array_map(function ($k, $v) {
        return $k . ': ' . $v;
    }, array_keys($head_arr), $head_arr);
    $ch       = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    if ($SSL === true) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    if ($data) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($ch, CURLOPT_REFERER, $refer);
    $cexecute = curl_exec($ch);
    curl_close($ch);

    if ($cexecute) {
        $result = $cexecute;
        return $result;
    } else {
        return false;
    }
}

function getLyc($id)
{
    $url     = 'http://music.163.com/api/song/lyric?id=' . $id . '&lv=-1&kv=-1';
    $json    = neteaseHttp($url);
    $lyc     = empty($json) ? false : json_decode($json, true);
    $lyc_txt = isset($lyc['lrc']['lyric']) ? $lyc['lrc']['lyric'] : false;
    return $lyc_txt;
}

function search($str)
{
    if ($str) {
        $url      = 'http://music.163.com/api/search/pc';
        $response = neteaseHttp($url, 's=' . urlencode($str) . '&offset=0&limit=10&type=1');
        $json     = json_decode($response, true);
        $list        = isset($json['result']['songs']) ? $json['result']['songs'] : null;
        if (!$list) {
            return false;
        }
        $arr = array();
        foreach ($list as $k => $v) {
            $url = 'http://music.163.com/song/media/outer/url?id=' . $v['id'] . '.mp3';
            if ($url) {
                $arr[$k]['title']  = $v['name'];
                $arr[$k]['author'] = $v['artists'][0]['name'];
                $pic               = $v['album']['picUrl'] . '?param=200y200';
                $arr[$k]['pic']    = str_replace("http:", "https:", $pic);
                $arr[$k]['url']    = str_replace("http:", "https:", $url);
                $arr[$k]['lyc']    = getLyc($v['id']);
            }
        }
        return json_encode($arr);
    }
}

function getJSON($playlist_id,$lyc = false)
{
    $url         = "https://music.163.com/api/playlist/detail?id=" . $playlist_id;
    $response    = neteaseHttp($url);
    $json        = json_decode($response, true);
    $list        = isset($json['result']['tracks']) ? $json['result']['tracks'] : null;
    if (!$list) {
        return null;
    }
    $arr = array();
    foreach ($list as $k => $v) {
        $url = 'http://music.163.com/song/media/outer/url?id=' . $v['id'] . '.mp3';
        if ($v['id']) {
            $arr[$k]['id'] = $v['id']; 
            $arr[$k]['title']  = $v['name'];
            $arr[$k]['author'] = $v['artists'][0]['name'];
            $pic               = $v['album']['picUrl'] . '?param=300y300';
            $arr[$k]['pic']    = str_replace("http:", "https:", $pic);
            $arr[$k]['url']    = $url;
            if($lyc === true){
                $arr[$k]['lyc']    = getLyc($v['id']);
            }
        }
    }
    return $arr;
}

function save($playlist_id,$dir = null,$lyc = true)
{
    if($dir){
        $filename = $dir .'/'. $playlist_id . '.json';
        if (is_file($filename)) {
              return file_get_contents($filename);
        }
    }
    $list = getJSON($playlist_id, $lyc);
    if($list!=null && isset($filename)) {
		$list = json_encode($list);
        file_put_contents($filename, $list);
    }
    return $list;
}
